package com.example.downloaddemo;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

/**
 * Created by xiewei on 15-2-3.
 */
public class DownLoader {
	private String urlstr;
	private String savepath;
	private String filepath;
	private int threadcount;
	private Context context;
	private Handler handler;
	private int filesize;
	private ArrayList<BlockInfo> infos=new ArrayList<BlockInfo>();
	private Dao dao;
	public int state=Constants.INIT;
	public DownLoader(String urlstr, String savepath, int threadcount, Context context, Handler handler) {
		this.context=context;
		this.handler=handler;
		this.savepath=savepath;
		this.threadcount=threadcount;
		this.urlstr=urlstr;
		this.filepath = savepath + urlstr.substring(urlstr.lastIndexOf("/"));
		Log.i("msg",filepath);

	}
	public LoadInfo getLoadInfo(){
		dao=new Dao(context);
		if (isFirst(urlstr)){
			initFile();
			int range=filesize/threadcount;
			infos=new ArrayList<BlockInfo>();
			for (int i = 0; i < threadcount-1; i++) {
				BlockInfo info=new BlockInfo(i,i*range,(i+1)*range,0,urlstr);
				infos.add(info);
			}
			BlockInfo info=new BlockInfo(threadcount-1,(threadcount-1)*range,filesize-1,0,urlstr);
			infos.add(info);
			dao.saveInfo(infos);
			LoadInfo loadInfo=new LoadInfo(urlstr,filesize,0);
			return loadInfo;
		}else{
			infos=dao.getInfos(urlstr);
			int complete=0;
			int size=0;
			for (BlockInfo info :infos){
				complete+=info.getCompeleteSize();
				size=size>info.getEndPos()?size:info.getEndPos();
			}
			size+=1;
			return  new LoadInfo(urlstr,size,complete);
		}
	}

	private void initFile() {
		RandomAccessFile accessFile = null;
		HttpURLConnection conn = null;
		try {
			URL url = new URL(urlstr);
			conn = (HttpURLConnection) url.openConnection();
			filesize = conn.getContentLength();
			File file = new File(filepath);
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			accessFile = new RandomAccessFile(file, "rwd");
			accessFile.setLength(filesize);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (accessFile != null) {
				try {
					accessFile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	private boolean isFirst(String urlstr) {
		return !dao.hasInfos(urlstr);
	}
	public void pause(){
		state=Constants.PAUSE;
	}
	public void delete(){
		dao.deleteInfo(urlstr);
	}
	public void download(){
		if (infos!=null){
			state=Constants.DOWNLOADING;
			for (BlockInfo info:infos){
				new DownThread(this,info,filepath,dao,handler).start();
			}
		}
	}
}
